package cn.dwong.msgGateway.controller;

import cn.dwong.msgGateway.base.ApiResponse;
import cn.dwong.msgGateway.base.LoginApiResponse;
import cn.dwong.msgGateway.entity.User;
import cn.dwong.msgGateway.entity.UserLogoutInfo;
import cn.dwong.msgGateway.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author 73202
 * @date 2022/3/9 15:24
 */
@RestController
@RequestMapping("/auth/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param user
     * @param result
     * @return
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public ApiResponse register(@Valid @RequestBody User user, BindingResult result){
        if (result.hasErrors()){
            return ApiResponse.ofBadRequest();
        }
        //添加到缓存中
        userService.register(user);
        return ApiResponse.ofSuccess();
    }

    /**
     * 登录
     * @param user
     * @param result
     * @return
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public ApiResponse login(@Valid @RequestBody User user, BindingResult result){
        if (result.hasErrors()){
            return ApiResponse.ofBadRequest();
        }
        if (userService.login(user)){
            //获取sessionId
            String sessionId = userService.getSessionId(user);
            if (!sessionId.equals(null)){
                return LoginApiResponse.ofLoginSuccess(sessionId);
            }else {
                return ApiResponse.ofInterNalServerError();
            }
        }
        return ApiResponse.ofBadRequest();
    }

    /**
     * 退出登录
     * @param result
     * @return
     */
    @PostMapping(value = "/logout")
    @ResponseBody
    public ApiResponse logout(@Valid @RequestBody UserLogoutInfo logoutInfo, BindingResult result){
        if (result.hasErrors()){
            return ApiResponse.ofBadRequest();
        }
        if (userService.logout(logoutInfo)){
            return ApiResponse.ofSuccess();
        }
        return ApiResponse.ofBadRequest();
    }

}
